import type { SafeUserData } from 'server/models/User'

interface LoginData {
  username: string
  password: string
}

interface LoginResponse {
  user: SafeUserData
}

interface ApiResponse<T> {
  success: boolean
  message: string
  data: T
}

export const useAuth = () => {
  // 用户状态
  const user = ref<SafeUserData | null>(null)
  const token = ref<string | null>(null)
  const isLoggedIn = computed(() => !!user.value && !!token.value)
  const isAdmin = computed(() => user.value?.role === 'admin')

  // 初始化认证状态
  const initAuth = () => {
    if (import.meta.client) {
      const storedToken = useCookie('auth_token').value
      const storedUser = localStorage.getItem('auth_user')
      
      if (storedToken && storedUser) {
        try {
          token.value = storedToken
          user.value = JSON.parse(storedUser)
        } catch (error) {
          console.error('解析用户数据失败:', error)
          clearAuth()
        }
      }
    }
  }

  // 登录
  const login = async (loginData: LoginData): Promise<{ success: boolean; message: string }> => {
    try {
      const response = await $fetch<ApiResponse<LoginResponse>>('/api/auth/login', {
        method: 'POST',
        body: loginData
      })

      if (response.success && response.data) {
        // 存储认证信息
        user.value = response.data.user

        if (import.meta.client) {
          localStorage.setItem('auth_user', JSON.stringify(response.data.user))
        }

        return { success: true, message: response.message || '登录成功' }
      } else {
        return { success: false, message: response.message || '登录失败' }
      }
    } catch (error: any) {
      console.error('登录错误:', error)
      
      // 处理API返回的错误
      if (error?.data?.message) {
        return { success: false, message: error.data.message }
      }
      
      return { success: false, message: '网络错误，请重试' }
    }
  }

  // 登出
  const logout = () => {
    user.value = null
    token.value = null

    if (import.meta.client) {
      localStorage.removeItem('auth_user')
      // 跳转到首页
      navigateTo('/')
    } else {
      // 服务器端环境，不进行页面跳转
      console.log('用户已登出（服务器端）')
    }
  }

  // 清除认证信息
  const clearAuth = () => {
    user.value = null
    token.value = null

    if (import.meta.client) {
      localStorage.removeItem('auth_user')
    }
  }

  // 检查token是否有效
  const checkAuth = async (): Promise<boolean> => {
    if (!token.value) {
      return false
    }

    try {
      // 可以调用一个验证token的API
      // const response = await $fetch('/api/auth/verify', {
      //   headers: { Authorization: `Bearer ${token.value}` }
      // })
      // return response.success
      
      // 暂时返回true，后续可以添加token验证API
      return true
    } catch (error) {
      console.error('Token验证失败:', error)
      clearAuth()
      return false
    }
  }

  // 获取认证头
  const getAuthHeaders = () => {
    if (token.value) {
      return {
        Authorization: `Bearer ${token.value}`
      }
    }
    return {}
  }

  // 带认证的API请求
  const fetchWithAuth = async <T>(url: string, options: any = {}): Promise<T> => {
    const headers = {
      ...options.headers,
      ...getAuthHeaders()
    }

    return await $fetch<T>(url, {
      ...options,
      headers
    })
  }

  return {
    // 状态
    user: readonly(user),
    token: readonly(token),
    isLoggedIn,
    isAdmin,
    
    // 方法
    initAuth,
    login,
    logout,
    clearAuth,
    checkAuth,
    getAuthHeaders,
    fetchWithAuth
  }
}